<template>
  <div class="login-container">
  <h2 class="login-title">用户登录</h2>
    <el-card class="login-card">
      <el-form ref="loginForm" :model="loginData" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginData.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios'
import { h } from 'vue'
import { ElMessage } from 'element-plus'
import {useCookies} from "vue3-cookies";
import router from '@/router';
const {cookies} = useCookies();

const loginData = ref({
  username: '',
  password: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
};

const submitForm = async () => {
  const {data} = await axios.post(
    "http://localhost:8080/api/auth/login",
    {
      username: loginData.value.username,
      password: loginData.value.password
    }
  )

  if (data.code != 200) {
    ElMessage({
      message: h(
        "span", null, "登录失败"
      )
    })
    return false;
  }

  console.log(data.data);

  // record login token
  cookies.set(data.data.tokenName, data.data.tokenValue, data.data.tokenTimeout);
  cookies.set("username", loginData.value.username, data.data.tokenTimeout);

  const token = cookies.get("satoken")
  const roleResponse = await axios.get(
    "http://localhost:8080/api/auth/getRole",
    {
      params: {
        username: loginData.value.username,
      },
      headers: {
        satoken: token,
      },
    }
  )
  const roleData = roleResponse.data
  console.log(roleData)

  if (roleData.code != 200) {
    ElMessage({
      message: h(
        "span", null, "登录失败"
      )
    })
    return false;
  }

  console.log(roleData);
  cookies.set("userRole", roleData.data, data.data.tokenTimeout);


  router.push({path:"/"}).then(() => {router.go()});
  
};

  

</script>

<style scoped>
.system-title {
  font-size: 48px;
  font-weight: bold;
  position: absolute;
  top: 16px;
  left: 16px;
}

.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  position: center;
  margin-top: -150px;
}

.login-title {
  font-size: 36px;
  font-weight: bold;
  margin-top: -50px; /* 将标题向上移动自身高度的一半，以使其垂直居中 */
}


.login-card {
  width: 400px;
  padding: 20px;
}

</style>
